
package com.compuvest.events;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.compuvest.web.AdvertArray;
import javax.servlet.annotation.WebServlet;

@WebServlet("/CompuVest/ChangeEvents/NewEvent")
public class NewEventServlet extends HttpServlet {

    public AdvertArray advertArray;

    private ServletContext context;

    static final String trustserver = "10.0.";

    @Override
    public void init(ServletConfig config) throws ServletException {
	super.init(config);

        context = config.getServletContext();

        advertArray = (AdvertArray)context.getAttribute("advertArray");
	if(advertArray == null) {
            System.out.println("NewEventServlet:init: advertArray==null");
	}
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String event = request.getParameter("compuvestevent");
        if(request.getRemoteAddr().contains(trustserver) && event != null) {

            if("excel".equals(event)) {
                 advertArray.refreshExcelFile();
            }

            PrintWriter out = response.getWriter();
            response.setContentType("text/xml;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");

            StringBuilder xml = new StringBuilder(200);
            xml.append("<?xml version='1.0' encoding='UTF-8'?>");
            xml.append("<status>");
            xml.append("<id>ok</id>");
            xml.append("</status>");

            out.print(xml.toString());
        }
    }
}
